<div class="row-content am-cf">
    <div class="row">
        <div class="am-u-sm-12 am-u-md-12 am-u-lg-12">
            <div class="widget am-cf">
                <div class="widget-head am-cf">
                    <div class="widget-title am-cf">分享树状图</div>
                </div>
                <div class="widget-body am-fr">
                     <div class="page_toolbar am-margin-bottom-xs am-cf">
                        <form class="toolbar-form" action="">
                            <input type="hidden" name="s" value="/<?= $request->pathinfo() ?>">
                            <div class="am-u-sm-12 am-u-md-3">
                                <div class="am-form-group">
                                    <div class="am-btn-toolbar">
                                        <div class="am-btn-group am-btn-group-xs">
                                            
                            
                                        </div>
                                    </div>
                                </div>
                            </div>
                           
                            <div class="am-u-sm-12 am-u-md-9">
                                <div class="am fr">
                                    
                                    <div class="am-form-group tpl-form-border-form am-fl">
                                        <input type="text" name="start_time"
                                               class="am-form-field"
                                               value="<?= $request->get('start_time') ?>" placeholder="请选择起始日期"
                                               data-am-datepicker>
                                    </div>
                                    <div class="am-form-group tpl-form-border-form am-fl">
                                        <input type="text" name="end_time"
                                               class="am-form-field"
                                               value="<?= $request->get('end_time') ?>" placeholder="请选择截止日期"
                                               data-am-datepicker>
                                    </div>
                                    <!-- <div class="am-form-group am-fl">
                                        <div class="am-input-group am-input-group-sm tpl-form-border-form">
                                            <input type="text" class="am-form-field" name="keyword"
                                                   placeholder="用户ID/用户昵称/手机号/姓名" value="<?= $request->get('keyword') ?>">
                                            <div class="am-input-group-btn">
                                                <button class="am-btn am-btn-default am-icon-search"
                                                        type="submit"></button>
                                            </div>
                                        </div>
                                    </div> -->
                                    <!-- 本页搜索（前端过滤，不提交表单） -->
<div class="am-form-group am-fl" style="margin-left:8px;">
  <div class="am-input-group am-input-group-sm tpl-form-border-form">
    <input type="text" class="am-form-field" id="client-keyword"
           placeholder="用户ID/姓名/手机号">
    <div class="am-input-group-btn">
      <!-- <button class="am-btn am-btn-primary" type="button" id="btn-client-search">
        <i class="am-icon-search"></i>
      </button> -->
      <button class="am-btn am-btn-default am-icon-search" type="button" id="btn-client-search"></button>
      <button class="am-btn" type="button" id="btn-client-clear">清空</button>
    </div>
  </div>
</div>
                                    <!-- 工具栏里搜索框旁边加导出按钮 -->
                                    <div class="am-form-group am-fl">
                                    <div class="am-btn-group am-btn-group-sm">
                                        <button id="btn-export" class="am-btn am-btn-secondary" type="button">
                                        <i class="am-icon-download"></i> 导出
                                        </button>
                                    </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="am-u-sm-12">
                        <style>
                            .sub-cat {
                                display: none;
                            }

                            /* 级别颜色 */
                            .level-1 {
                                background-color: #f2f9ff;
                            }

                            .level-2 {
                                background-color: #fef6e7;
                            }

                            .level-3 {
                                background-color: #eaf7ea;
                            }

                            .level-4 {
                                background-color: #fce8ef;
                            }

                            .level-5 {
                                background-color: #f5f5f5;
                            }

                            /* 图标对齐 */
                            .toggle-sub {
                                cursor: pointer;
                                margin-right: 5px;
                            }
                        </style>

                        <table width="100%" class="am-table am-table-compact am-table-striped tpl-table-black">
                            <thead>
                            <tr>
                                <th>用户 ID</th>
                                <th>用户名</th>
                                <th>电话</th>
                                <th>级别</th>
                                <th>时间</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php if (!empty($tree)): ?>
                                <?php
                                function renderTree($node, $level = 1, $parentId = 0) {
                                    $hasChild = !empty($node['child']);
                                    $rowClass = $level == 1 ? 'parent-cat level-'.$level : 'sub-cat level-'.$level;
                                    $rowAttr = $level == 1
                                        ? 'data-id="'.$node['category_id'].'"' 
                                        : 'data-parent="'.$parentId.'" data-id="'.$node['category_id'].'"';

                                    $toggleIcon = $hasChild
                                        ? '<i class="am-icon-plus-square toggle-sub" data-id="'.$node['category_id'].'"></i>'
                                        : '<span style="display:inline-block;width:14px;"></span>';

                                    $name = empty($node['name']) ? '未知姓名' : $node['name'];
                                    $phone = isset($node['phone']) && $node['phone'] !== '' ? $node['phone'] : '—';

                                    echo '<tr class="'.$rowClass.'" '.$rowAttr.'>';
                                    echo '<td class="am-text-middle">'.$node['category_id'].'</td>';
                                    echo '<td class="am-text-middle">'.$toggleIcon.$name.'</td>';
                                    echo '<td class="am-text-middle">'.$phone.'</td>';
                                    echo '<td class="am-text-middle">'.$level.'</td>';
                                    echo '<td class="am-text-middle">'.$node['create_time'].'</td>';
                                    echo '</tr>';

                                    if ($hasChild) {
                                        foreach ($node['child'] as $child) {
                                            renderTree($child, $level + 1, $node['category_id']);
                                        }
                                    }
                                }
                                foreach ($tree as $node) {
                                    renderTree($node);
                                }
                                ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="am-text-center">暂无记录</td>
                                </tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(function () {
  // 默认折叠所有子项
  $('tr.sub-cat').hide();

  // ===== 树结构索引（一次构建，后面搜索复用）=====
  const rowById = {};         // id -> jQuery <tr>
  const childrenMap = {};     // parentId -> [childId, ...]
  const parentMap = {};       // id -> parentId

  $('tbody tr').each(function () {
    const $tr = $(this);
    const id = String($tr.data('id'));
    const p  = String($tr.data('parent') || '0');

    rowById[id] = $tr;
    parentMap[id] = p;

    if (!childrenMap[p]) childrenMap[p] = [];
    childrenMap[p].push(id);
  });

  // ====== 原有的展开/收起 ======
  $(document).on('click', '.toggle-sub', function () {
    const $icon = $(this);
    const catId = String($icon.data('id'));
    const isOpen = $icon.hasClass('am-icon-minus-square');

    if (isOpen) {
      $icon.removeClass('am-icon-minus-square').addClass('am-icon-plus-square');
      hideAllChildren(catId);
    } else {
      $icon.removeClass('am-icon-plus-square').addClass('am-icon-minus-square');
      showDirectChildren(catId);
    }
  });

  function hideAllChildren(parentId) {
    (childrenMap[parentId] || []).forEach(function (cid) {
      const $row = rowById[cid];
      $row.hide();
      $row.find('.toggle-sub')
          .removeClass('am-icon-minus-square')
          .addClass('am-icon-plus-square');
      hideAllChildren(cid);
    });
  }

  function showDirectChildren(parentId) {
    (childrenMap[parentId] || []).forEach(function (cid) {
      rowById[cid].show();
    });
  }

  // ====== 本页搜索：关键函数 ======
  function filterTree(keyword) {
    keyword = $.trim(keyword);
    if (!keyword) {
      // 恢复初始：全部显示，再折叠为默认状态（只显示顶级）
      $('tbody tr').show();
      // 折叠所有子项
      $('tr.sub-cat').hide();
      // 图标复原为 +
      $('.toggle-sub').removeClass('am-icon-minus-square').addClass('am-icon-plus-square');
      return;
    }

    // 1) 全部隐藏
    $('tbody tr').hide();
    $('.toggle-sub').removeClass('am-icon-minus-square').addClass('am-icon-plus-square');

    // 2) 找到命中行（ID/姓名/手机号/整行文本都可匹配）
    const hits = [];
    $.each(rowById, function (id, $tr) {
      const text = $tr.text();
      const phone = $tr.find('td').eq(2).text();
      if (
        id.indexOf(keyword) !== -1 ||
        text.indexOf(keyword) !== -1 ||
        (phone && phone.indexOf(keyword) !== -1)
      ) {
        hits.push(id);
      }
    });

    if (hits.length === 0) return; // 没命中就全隐藏（保持静默）

    // 3) 展示命中节点、它的全部下级、以及到根的所有上级
    const showSet = new Set();

    function addDescendants(id) {
      showSet.add(id);
      (childrenMap[id] || []).forEach(function (cid) {
        addDescendants(cid);
      });
    }

    function addAncestors(id) {
      let cur = id;
      while (parentMap[cur] && parentMap[cur] !== '0') {
        const p = parentMap[cur];
        showSet.add(p);
        cur = p;
      }
      // 顶级(没有 parent 或 parent==0)也要显示
      showSet.add(cur);
    }

    hits.forEach(function (id) {
      addDescendants(id);
      addAncestors(id);
    });

    // 4) 真正显示这些行
    showSet.forEach(function (id) {
      const $row = rowById[id];
      if ($row) $row.show();
    });

    // 5) 自动展开有可见子项的父节点（把 +/- 图标置为 -）
    showSet.forEach(function (id) {
      const kids = (childrenMap[id] || []).filter(cid => showSet.has(cid));
      if (kids.length > 0) {
        const $icon = rowById[id].find('.toggle-sub');
        if ($icon.length) {
          $icon.removeClass('am-icon-plus-square').addClass('am-icon-minus-square');
        }
      }
    });
  }

  // 绑定本页搜索按钮与回车
  $('#btn-client-search').on('click', function () {
    filterTree($('#client-keyword').val());
  });
  $('#client-keyword').on('keypress', function (e) {
    if (e.which === 13) {
      e.preventDefault();
      filterTree($('#client-keyword').val());
    }
  });
  $('#btn-client-clear').on('click', function () {
    $('#client-keyword').val('');
    filterTree('');
  });

  // ===== 保留你原来的导出 =====
  $('#btn-export').on('click', function () {
    var params = $('.toolbar-form').find(':input').not('[name="s"]').serialize();
    var baseUrl = "<?= url('store/apps.dealer.withdraw/export') ?>";
    window.location = baseUrl + (params ? ('?' + params) : '');
  });
});
</script>